﻿Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text





Module Utils



    ''' <summary>
    '''  调整图像到指定大小
    ''' </summary>
    ''' <param name="imageFile"></param>
    ''' <param name="targetSize"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ResizeImageFile(ByVal imageFile As Byte(), ByVal targetSize As Integer) As Byte()
        Dim original = Image.FromStream(New MemoryStream(imageFile))

        Dim targetH, targetW As Integer

        If original.Height > original.Width Then

            targetH = targetSize
            targetW = CInt(original.Width * (CDbl(targetSize) / CDbl(original.Height)))


        Else

            targetW = targetSize
            targetH = CInt(original.Height * (CDbl(targetSize) / CDbl(original.Width)))
        End If

        Dim imgPhoto = Image.FromStream(New MemoryStream(imageFile))
        ' Create a new blank canvas.  The resized image will be drawn on this canvas.
        Dim bmPhoto = New Bitmap(targetW, targetH, PixelFormat.Format24bppRgb)
        bmPhoto.SetResolution(72, 72)
        Dim grPhoto = Graphics.FromImage(bmPhoto)
        grPhoto.SmoothingMode = SmoothingMode.AntiAlias
        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic
        grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality
        grPhoto.DrawImage(imgPhoto, New Rectangle(0, 0, targetW, targetH), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel)
        'Save out to memory and then to a file.  We dispose of all objects to make sure the files don't stay locked.
        Dim mm As New MemoryStream()
        bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg)
        original.Dispose()
        imgPhoto.Dispose()
        bmPhoto.Dispose()
        grPhoto.Dispose()
        Return mm.GetBuffer()


    End Function


    ''' <summary>
    '''创建MD5 Hash 字符串
    ''' </summary>
    ''' <param name="input"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function CalculateMD5Hash(ByVal input As String) As String
        ' step 1, calculate MD5 hash from input
        Dim md5 = System.Security.Cryptography.MD5.Create()
        Dim inputBytes = System.Text.Encoding.UTF8.GetBytes(input)
        Dim hash = md5.ComputeHash(inputBytes)

        ' step 2, convert byte array to hex string
        Dim sb As New StringBuilder()
        For i = 0 To hash.Length - 1
            sb.Append(hash(i).ToString("X2"))
        Next
        Return sb.ToString()

    End Function

End Module
